﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Navigant.Model.PreservationNotices;

namespace Navigant.Web.UI
{
    public class PreservationNoticeGridViewTemplate : ITemplate
    {
        private DataControlRowType rowType;

        public PreservationNoticeGridViewTemplate(DataControlRowType rowType)
        {
            this.rowType = rowType;
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            if (this.rowType == DataControlRowType.DataRow)
            {
                HtmlAnchor anchor = new HtmlAnchor();
                anchor.DataBinding += new System.EventHandler(this.anchor_DataBinding);
                container.Controls.Add(anchor);
            }
        }

        #endregion

        private void anchor_DataBinding(object sender, EventArgs e)
        {
            // Get the HtmlAnchor control to bind the value. The HtmlAnchor control
            // is contained in the object that raised the DataBinding 
            // event (the sender parameter).
            HtmlAnchor anchor = sender as HtmlAnchor;

            // Get the GridViewRow object that contains the Label control.
            GridViewRow row = anchor.NamingContainer as GridViewRow;

            // Get the field value from the GridViewRow object and 
            // assign it to the GridViewRow control.
            PreservationNotice notice = null;
            if (row != null)
            {
                notice = row.DataItem as PreservationNotice;
            }

            if (anchor != null && notice != null)
            {
                // Build the hyperlink to the notice message page
                anchor.HRef = string.Format("{0}/_layouts/NavigantPages/PreservationNoticeView.aspx?noticeId={1}",
                    notice.ParentCase.SiteAddress.AbsoluteUri, notice.Id);
                anchor.Target = "_blank";
                if (notice.Template != null && !string.IsNullOrEmpty(notice.Template.Name))
                {
                    anchor.InnerHtml = notice.Template.Name;
                }
            }
        }
    }
}
